<template>
  <div class="table-data">
    <el-form
      :rules="rules"
      ref="ruleForm"
      :model="form"
      size="small"
      class="form-box"
    >
    
    <!-- <p class="title">基础信息设置</p> -->
    <el-tabs type="border-card">
      <el-tab-pane label="基础信息">
        <el-form-item label="商品标题" prop="title">
          <el-input type="text" v-model="form.title" placeholder="请输入商品标题"></el-input>
        </el-form-item>
        <!-- <el-form-item label="商品副标题" prop="sub_title">
          <el-input type="text" v-model="form.sub_title" placeholder="请输入商品副标题"></el-input>
        </el-form-item> -->
        <el-form-item prop="cover">
          <label for="verify_hour" class="el-form-item__label form-label">封面图片</label>
          <uploadImg @bindSendImg="propImg" :key="timer" :imgUrl="form.cover"></uploadImg>
        </el-form-item>
        <el-form-item label="商品轮播图">
          <uploadImgList @bindSendImgList="propImgList" :key="timer" :imgUrl="form.images"></uploadImgList>
        </el-form-item>
        <el-form-item prop="poster" label="商品海报图">
            <img :src="form.share.share_bg" @click="codeediting" v-if="form.share.share_bg" class="share_bg">
            <posterUploadImg @bindSendImg="posterImg" :key="timer" :imgUrl="form.share.share_bg" v-if="!form.share.share_bg"></posterUploadImg>
          </el-form-item>
        <el-form-item label="商品类型" prop="verify_type">
          <el-radio-group v-model="form.verify_type ">
            <!-- <el-radio :label="0">物流商品</el-radio>
            <el-radio :label="1">核销商品</el-radio> -->
            <el-radio :label="'ship'" :disabled='label=="ship"?false:true'>物流商品</el-radio>
            <el-radio :label="'code'" :disabled='label=="code"?false:true'>核销商品</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="制码模式" prop="ticket_type">
          <el-radio-group v-model="form.ticket_type">
            <el-radio :label="1" :disabled='label==1?false:true'>自建商品</el-radio>
            <el-radio :label="2" :disabled='label==2?false:true'>导码商品</el-radio>
            <el-radio :label="3" :disabled='label==3?false:true'>制码商品</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="售卖时间">
          <el-date-picker
              v-model="saleDateTime"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
              >
            </el-date-picker>
        </el-form-item>
        <el-form-item label="是否可退" prop="refund_able">
          <el-radio-group v-model="form.refund_able">
            <el-radio :label="1">可以退</el-radio>
            <el-radio :label="0">不可退</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上下架状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="2">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="供应商" prop="vendor_id">
          <el-select v-model="form.vendor_id" filterable clearable placeholder="供应商">
            <el-option v-for="item in supplierList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属商家" prop="shop_id" v-if="form.vendor_id==1">
          <el-select v-model="form.shop_id" filterable clearable placeholder="所属商家">
            <el-option v-for="item in businessList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品所属标签" prop="application">
          <el-select v-model="form.tag_ids" multiple placeholder="请选择">
            <el-option
            v-for="item in labelList"
            :key="item.id"
            :label="item.tag"
            :value="item.id">
            {{item.tag}}-{{item.id}}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品所属分类">
          <!-- <el-cascader
            :options="form.location"
            v-model="kindList"
            @change="handleChange">
          </el-cascader> -->
          <el-select v-model="form.cate_id" clearable placeholder="一级分类" @change="handleChange">
            <el-option v-for="item in kindList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <el-select v-model="form.sub_cate_id" clearable placeholder="二级分类" @change="handleChangeTwo" style="margin:0 10px">
            <el-option v-for="item in kindListTwo" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <el-select v-model="form.third_sub_cate_id" clearable placeholder="三级分类">
            <el-option v-for="item in kindListThree" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="购买须知">
        <el-form-item label="" prop="application">
          <ueditor :content="form.remark" :key="timer"  @ueditor-change="editorChangeRemark"></ueditor>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="商品详情">
        <ueditor :content="form.describe" :key="timer" @ueditor-change="editorChange"></ueditor>
      </el-tab-pane>
      <el-tab-pane label="核销码">
        <el-form-item label="与商家结算时机" prop="verify_way">
          <el-select v-model="form.verify_way" clearable placeholder="请选择">
            <el-option  :key="1" label="核销后几天" :value="1" v-if="form.verify_type!=='ship'"></el-option>
            <el-option  :key="2" label="发货后几天" :value="2" v-if="form.verify_type!=='code'"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="具体几天" prop="verify_day">
          <el-input type="number" min="0" v-model="form.verify_day"></el-input>
        </el-form-item>
        <el-form-item  v-if="form.verify_type!='ship'" label="一个商品生成的核销数码数量（无关规格）" prop="create_ticket_num">
          <el-input type="number" min="1" v-model="form.create_ticket_num"></el-input>
        </el-form-item>
        <el-form-item  v-if="form.verify_type!='ship'" label="核销码保护期">
          <el-input type="text" v-model="form.verify_hour"></el-input>
        </el-form-item>
        <el-form-item  v-if="form.verify_type!='ship'">
          <label for="verify_hour" class="el-form-item__label form-label">核销码有效期</label>
          <el-date-picker
              v-model="dateTime"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
              >
            </el-date-picker>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="价格设置">
        <el-row>
          <el-col :span="24">
            <el-form-item label="友情提醒"><label for="">商家结算价 <= 渠道结算价 <= 建议零售价 <= 原价</label></el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品规格" prop="guige">
              <el-radio-group v-model="guige">
                <el-radio :label="1">单规格</el-radio>
                <el-radio :label="2">多规格</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="guige==2">
            <el-form-item label="商品规格" prop="spec">
              <div class="specBox">
                <ul>
                  <li v-for="(specItem, i) in specItems" :key="i">
                    <el-input v-model="specItem.standardValue" style="width: 220px"  @blur.prevent="setParentInput(specItem.standardValue, i)" placeholder="请填写规格名称(如：颜色)"></el-input>
                    <el-input v-model="specItem.specName" style="width: 220px" placeholder="请填写规格值(如：红色)"></el-input>
                    <el-button type="primary" class="button" size="small" @click="addSpecVal(i)">添加</el-button>
                    <el-button type="danger" size="small" @click="delliEle(i)">删除</el-button>
                    <div>
                      <el-tag v-for="(item,index) in specItem.specNames" closable :disable-transitions="false" :key="item" @close="closeTag(i, index)">{{item}}</el-tag>
                    </div>
                  </li>
                </ul>
                <el-button type="primary" size="small" @click="add()">添加规格</el-button>
                <el-form>
                  <table class="specTable">
                    <thead>
                      <th v-for="(th,i) in addSpec" :key="i">{{th.item}}</th>
                      <th v-if="form.verify_type!='ship'">每个核销码商家结算价</th>
                      <th>商家结算价</th>
                      <th v-if="form.verify_type!='ship'">每个核销码默认渠道结算价</th>
                      <th>渠道商结算价</th>
                      <th>原价</th>
                      <th>建议售价</th>
                      <th>库存</th>
                      <th>重量（单位kg）</th>
                      <!-- <th>操作</th> -->
                    </thead>
                    <tbody>
                      <tr v-for="(tr, index) in result_spec" :key="index">
                        <td v-for="(td,i) in tr.td" :key="i">{{td}}</td>
                        <td><el-input size="mini" @blur="getSellPrice(result_spec[index].sell_price, index)" v-model.number="result_spec[index].sell_price" type="number" min="1"></el-input></td>
                        <td v-if="form.verify_type!='ship'">{{result_spec[index].supplierPrice}}</td>
                        <td><el-input size="mini"  @blur="getChannelPrice(result_spec[index].channel_settle_price, index)" type="number" min="1" v-model.number="result_spec[index].channel_settle_price"></el-input></td>
                        <td v-if="form.verify_type!='ship'">{{result_spec[index].channelPrice}}</td>
                        <td><el-input size="mini" @blur="getOriginalPrice(result_spec[index].original_price, index)" type="number" min="1" v-model.number="result_spec[index].original_price"></el-input></td>
                        <td><el-input size="mini" @blur="getSuggestPrice(result_spec[index].suggest_price, index)" type="number" min="1" v-model.number="result_spec[index].suggest_price"></el-input></td>
                        <td><el-input size="mini" @blur="getStock(result_spec[index].stock, index)" type="number" min="1" v-model.number="result_spec[index].stock"></el-input></td>                      
                        <td><el-input size="mini" type="number" min="1" v-model="result_spec[index].weight"></el-input></td>                      
                      </tr>
                    </tbody>
                  </table>
                </el-form>
              </div>
            </el-form-item>
          </el-col>
          <el-col v-else>
            <el-col :span="24" v-if="form.verify_type=='ship'">
              <p class="price-title">价格设置自营物流产品</p>
              <el-form-item label="商家结算价" prop="merchant_settle_price">
                <el-input type="number" @blur="getSellPrices(form.merchant_settle_price)" min="1" v-model.number="form.merchant_settle_price"></el-input>
              </el-form-item>
              <el-form-item label="渠道结算价" prop="channel_settle_price">
                <el-input type="number" @blur="getChannelPrices(form.channel_settle_price)" min="1" v-model.number="form.channel_settle_price"></el-input>
              </el-form-item>
              <el-form-item label="原价" prop="original_price">
                <el-input type="number" @blur="getOriginalPrices(form.original_price)" min="1" v-model.number="form.original_price"></el-input>
              </el-form-item>
              <el-form-item label="建议零售价" prop="suggest_price">
                <el-input type="number" @blur="getSuggestPrices(form.suggest_price)" min="1" v-model.number="form.suggest_price"></el-input>
              </el-form-item>
              <el-form-item label="库存" prop="stock">
                <el-input type="number" min="1" v-model.number="form.stock"></el-input>
              </el-form-item>
              <el-form-item label="重量（单位kg）" prop="weight">
                <el-input type="number" min="0" v-model.number="form.weight"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-else>
              <el-form-item label="每个核销码供应商结算价" prop="vendor_settle_price">
                <el-input type="number" min="1" v-model.number="form.vendor_settle_price" @blur="getSupplierPrices()"></el-input>
              </el-form-item>
              <el-form-item label="单商品供应商算价">
                <span class="price-txt">{{supplierPrice}}</span>
                <span class="price-tip">每个核销码供应商结算价*单个商品生成码数量</span>
              </el-form-item>
              <el-form-item label="每个核销码默认渠道结算价" prop="channel_settle_price">
                <el-input type="number" min="1" v-model.number="form.channel_settle_price" @blur="getchannelPricess()"></el-input>
              </el-form-item>
              <el-form-item label="单商品渠道结算价">
                <span class="price-txt">{{channelPrice}}</span>
                <span class="price-tip">每个核销码默认渠道结算价*单个商品生成码数量</span>
              </el-form-item>
              <el-form-item label="原价" prop="original_price">
                <el-input type="number" @blur="getOriginalPrices(form.original_price)" min="1" v-model.number="form.original_price"></el-input>
              </el-form-item>
              <el-form-item label="建议售价（单个商品，非单个核销码）" prop="suggest_price">
                <el-input type="number" @blur="getSuggestPrices(form.suggest_price)" min="1" v-model.number="form.suggest_price"></el-input>
              </el-form-item>
              <el-form-item label="库存" prop="stock">
                <el-input type="number" min="1" v-model.number="form.stock"></el-input>
              </el-form-item>
              <!-- <el-form-item label="重量（单位g）" prop="weight">
                <el-input type="number" min="1" v-model="form.weight"></el-input>
              </el-form-item> -->
            </el-col>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="物流设置" v-if="form.verify_type=='ship'">
        <el-form-item label="物流信息" prop="title">
          <el-radio-group v-model="form.client" @change="shippingChange()">
            <el-row>
              <el-col :span="24" style="margin-bottom:18px">
                <el-radio :label="0">统一运费</el-radio>
                <el-input type="text" v-model="form.shipping_price" @focus="shippingChange1(0)"></el-input>
              </el-col>
              <el-col :span="24">
                <el-radio :label="1">运费模板</el-radio>
                <el-select v-model="form.shipping_id" clearable placeholder="请选择" @focus="shippingChange1(1)">
                  <el-option v-for="item in shippingTemplateList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-col>
            </el-row>
          </el-radio-group>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="留言模板">
        <el-form-item label="留言模板">
          <el-select v-model="form.mt_id" clearable placeholder="请选择">
            <el-option v-for="mtItem in messageTemplateList"  :key="mtItem.mt_id" :label="mtItem.mt_name" :value="mtItem.mt_id"></el-option>
          </el-select>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="门票选择（仅限票付通产品）" v-if="form.vendor_id==5">
        <el-table ref="multipleTable" :data="verifyList" tooltip-effect="dark" style="width: 100%;" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="title" label="门票名称"  width="210">
            <template slot-scope="scope">
              <el-input type="text" v-model="scope.row.title"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="order_start" label="开始时间"></el-table-column>
          <el-table-column prop="order_end" label="结束时间"></el-table-column>
          <el-table-column prop="type_txt" label="有效期类型"></el-table-column>
          <el-table-column prop="settle_price" label="结算价"></el-table-column>
          <el-table-column prop="price" label="售价"></el-table-column>
          <el-table-column prop="stock_real" label="库存"></el-table-column>
          <el-table-column prop="user_price" label="自定义售价"  width="210">
            <template slot-scope="scope">
              <el-input type="text" v-model="scope.row.user_price"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    </el-form>
    <div class="dialog-footer">
      <el-button @click="cancel" size="small">取消</el-button>
      <el-button @click="submitFormAdd('ruleForm')" type="primary" size="small">确定</el-button>
    </div>
     <AppletPoster :isImport="isImport" :isPoster="isPoster" :key="timer" :posterImg="form.share.share_bg"  @closeDialog="closeDialog" @closeDialog1="closeDialog1" :formDate="form" @determine="determine"></AppletPoster>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Provide, Watch } from "vue-property-decorator";
import ueditor from "@/components/ueditor/index.vue";
import uploadImg from "@/components/uploadImg/index.vue";
import uploadImgList from "@/components/uploadImg/list.vue";
import goodsApi from "@/api/goods";
import businessApi from "@/api/business";
import supplierApi from "@/api/supplier";
import AppletPoster from "./AppletPoster.vue";
import posterUploadImg from "@/components/uploadImg/poster.vue";
@Component({
  components: {AppletPoster,posterUploadImg,uploadImg,uploadImgList,ueditor}
})
export default class goodsAddDialog extends Vue {
  // 属性或参数中使用 ！：表示强制解析（告诉typescript编译器，这里一定有值），常用于vue-decorator中的@Prop
  check:boolean = true//防重复提交
  label :any = ''
  verifyList:any = []
  @Provide() timer:any=''
  @Provide() dateTime: any = [];//核销时间
  @Provide() saleDateTime: any = [];//售卖时间
  @Provide() value1: any = [];
  @Provide() imgList: any=[];//轮播列表
  @Provide() labelList: any=[];//标签列表
  @Provide() supplierList: any=[];//供应商列表
  @Provide() businessList: any=[];//商家列表
  @Provide() advertiser: any = [];//广告商
  @Provide() kindList: any = [];//所属分类列表
  @Provide() shippingTemplateList: any = []; //运费模板问题
  @Provide() messageTemplateList: any = []; //运费模板问题
  @Provide() kindListTwo: any = [];//所属分类列表
  @Provide() kindListThree: any = [];//所属分类列表
  @Provide() state: boolean = false; // 状态默认值
  @Provide() guige: any = 1; // 规格
  @Provide() supplierPrice: any = ""; // 供应商算价
  @Provide() channelPrice: any = ""; // 渠道结算价
  @Provide() isPoster: Boolean = false; // 是否展示导出弹窗
  @Provide() isImport: Boolean = false; // 是否展示导入弹窗
  @Provide() tag_ids: any = []; // 标签id
  @Provide() searchMapS:{//供应商查询条件
    name: string,
    phone:string,
  }={
    name:'',
    phone:''
  }
  @Provide() searchMapB:{
    keyword: string,
    cate_id: string,
    is_child: any,
  }={
    keyword: "",
    cate_id: "",
    is_child: 0
  }
  @Provide() searchItem:{
    item: string,
    parent_id: string,
    goods_id: any,
  }={
    item: "",
    parent_id: "",
    goods_id: ""
  }
  @Provide() searchItem2:{
    item: string,
    parent_id: string,
    goods_id: any,
  }={
    item: "",
    parent_id: "",
    goods_id: ""
  }
  @Provide() allDatas:any={}
  form:any={
    id:"",
    barcode:"",
    title:'',
    sub_title:'',
    cate_id:'',
    sub_cate_id:'',
    third_sub_cate_id:'',
    brand_id:'',
    stock:'',
    shipping_id:'',
    mt_id:0,
    shipping_price:'',
    weight:'',
    cubage:'',
    status:'',
    price:'',
    cover:'',
    client:'',
    sale_on_time:'',
    sale_off_time:'',
    original_price:'',
    vendor_price:'',
    vendor_settle_price:'',
    channel_settle_price:'',
    merchant_settle_price:'',
    suggest_price:'',
    unit_name:'',
    vendor_id:'',
    shop_id:'',
    refund_able:'',
    ticket_type:'',
    verify_type:'',
    verify_way:'',
    verify_day:'',
    verify_start_time:'',
    verify_end_time:'',
    verify_hour:'',
    verify_ticket_num:'',
    create_ticket_num:'',
    describe:'',
    images:[],
    spec_item:[],
    spec_goods_price:[],
    share:{
      type:'',
      share_bg:'',
      qr_y:0,
      qr_x:0
    },
    pft_ticket:[]
  };
   rules: any = {
    title: [{ required: true, message: "请输入商品标题", trigger: "blur" }],
    stock: [{ required: true, message: "请输入库存", trigger: "blur" }],
    shipping_price: [{ required: true, message: "请输入运费价格", trigger: "blur" }],
    vendor_id: [{ required: true, message: "请选择供应商", trigger: "change" }],
    shop_id: [{ required: true, message: "请选择所属商家", trigger: "change" }],
    weight: [{ required: true, message: "请输入重量", trigger: "blur" }],
    price: [{ required: true, message: "请输入售价", trigger: "blur" },{
        //pattern: /^[1-9]\d*(\.\d+)?$/,  //大于1
        pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/,  //正则
        message: '请输入大于0的数'
      }],
    original_price: [{ required: true, message: "请输入原价", trigger: "blur" },{
        //pattern: /^[1-9]\d*(\.\d+)?$/,  //大于1
        pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/,  //正则
        message: '请输入大于0的数'
      }],
    channel_settle_price: [{ required: true, message: "请输入渠道结算价", trigger: "blur" }
    // ,{
      //pattern: /^[1-9]\d*(\.\d+)?$/,  //大于1
      //   pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/,  //正则
      //   message: '请输入大于0的数'
      // }
      ],
    merchant_settle_price: [{ required: true, message: "请输入商家结算价", trigger: "blur" },{
        //pattern: /^[1-9]\d*(\.\d+)?$/,  //大于1
        pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/,  //正则
        message: '请输入大于0的数'
      }],
    suggest_price: [{ required: true, message: "请输入建议零售价", trigger: "blur" },{
        //pattern: /^[1-9]\d*(\.\d+)?$/,  //大于1
        pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/,  //正则
        message: '请输入大于0的数'
      }],
    refund_able: [{ required: true, message: "请选择是否可退", trigger: "change" }],
    status: [{ required: true, message: "请选择上下架", trigger: "change" }],
    ticket_type: [{ required: true, message: "请选择制码模式", trigger: "change" }],
    verify_type: [{ required: true, message: "请选择商品类型", trigger: "change" }],
    verify_way: [{ required: true, message: "请选择与商家结算时机", trigger: "change" }],
    verify_day: [{ required: true, message: "请输入具体几天", trigger: "blur" },{
        //pattern: /^[1-9]\d*(\.\d+)?$/,  //大于1
        pattern: /^([1-9]\d*(\.\d+)?|0)$/,  //正则
        message: '请输入大于等于0的数'
      }],
    verify_hour: [{ required: true, message: "请输入核销码保护期", trigger: "blur" },{
        //pattern: /^[1-9]\d*(\.\d+)?$/,  //大于1
        pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/,  //正则
        message: '请输入大于0的数'
      }],
    describe: [{ required: true, message: "请输入商品详情描述", trigger: "blur" }],
    verify_ticket_num: [{ required: true, message: "请输入单个商品可使用次数", trigger: "blur" },{
        //pattern: /^[1-9]\d*(\.\d+)?$/,  //大于1
        pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/,  //正则
        message: '请输入大于0的数'
      }],
    create_ticket_num: [{ required: true, message: "请输入单个商品生成核销码数量", trigger: "blur" },{
        //pattern: /^[1-9]\d*(\.\d+)?$/,  //大于1
        pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/,  //正则
        message: '请输入大于0的数'
      }],
  };
  @Provide() specItems:any= []  // 规格数组
  @Provide() result_spec:any= []  // 
  @Provide() show:boolean= false  // 
  @Provide() disable:boolean= false  // 
  @Provide() arr:any= []  //
  @Provide() addSpec:any= []  //
  @Provide() result:any= []  //
  @Provide() seleIndex:any= []  //多规格选中输入框的下标（商家结算价）
  @Provide() seleVal:any= []  //多规格选中输入框的值（商家结算价）
  @Provide() channelIndex:any= []  //多规格选中输入框的下标（渠道结算价）
  @Provide() channelVal:any= []  //多规格选中输入框的值（渠道结算价）
  // 监听商家结算价
  @Watch('form.shipping_id')
	getClient(newVal){
    if(newVal!==''){
      this.form.client = 1
    }else {
      this.form.client =0
    }
  }
  @Watch("form.vendor_settle_price")
  getSupplierPrice(){
    this.supplierPrice=this.form.vendor_settle_price*this.form.create_ticket_num
  }
  getSupplierPrices(val){
  }
  @Watch("form.channel_settle_price")
  getchannelPrices(){
    this.channelPrice=this.form.channel_settle_price*this.form.create_ticket_num
  }
  getchannelPricess(val){
    if(val<this.form.vendor_settle_price){
      this.$message({
        message: '渠道结算价必须大于供应商结算价',
        type: "error"
      });
    }
  }
  @Watch("form.create_ticket_num")
  getTicketNum(){
    this.supplierPrice=this.form.vendor_settle_price*this.form.create_ticket_num
    this.channelPrice=this.form.channel_settle_price*this.form.create_ticket_num
    // this.trsVals.forEach(item=>{
    //   item.supplierPrice=item.sell_price*this.form.create_ticket_num
    //   item.channelPrice=item.channel_settle_price*this.form.create_ticket_num
    // })
  }
  getSellPrices(val){
  }
  getChannelPrices(val){
    if(val<this.form.merchant_settle_price){
      this.$message({
        message: '渠道结算价必须大于商家结算价',
        type: "error"
      });
    }
  }
  getOriginalPrices(val){
    if(val<this.form.suggest_price || val<this.form.channel_settle_price){
      this.$message({
        message: '原价必须大于等于建议零售价、商家结算价、渠道结算价',
        type: "error"
      });
    }
  }
  getSuggestPrices(val){
    if(val>this.form.original_price){
      this.$message({
        message: '建议零售价必须小于等于原价',
        type: "error"
      });
      return;
    }
  }
  // 验证每个核销码商家结算价是否大于0
  getSellPrice(val, index) {
    if (Number(val) <= 0) {
      this.result_spec[index].sell_price = null;
      this.$message({
        message: '商家结算价必须大于0',
        type: "error"
      });
      return;
    }
  }
  // 验证每个核销码渠道结算价是否大于0
  getChannelPrice(val, index) {
    if (Number(val) <= 0) {
      this.result_spec[index].channel_settle_price = null;
      this.$message({
        message: '渠道结算价必须大于0',
        type: "error"
      });
      return;
    }
    if(val<this.result_spec[index].sell_price){
      this.$message({
        message: '渠道结算价必须大于商家结算价',
        type: "error"
      });
    }
  }
  // 验证原价是否大于0
  getOriginalPrice(val, index) {
    if (Number(val) <= 0) {
      this.result_spec[index].original_price = null;
      this.$message({
        message: '原价必须大于0',
        type: "error"
      });
      return;
    }
    if(val<this.result_spec[index].suggest_price || val<this.result_spec[index].channel_settle_price){
      this.$message({
        message: '原价必须大于等于建议零售价、商家结算价、渠道结算价',
        type: "error"
      });
    }
  }
  // 验证建议零售价是否大于0
  getSuggestPrice(val, index) {
    if (Number(val) <= 0) {
      this.result_spec[index].suggest_price = null;
      this.$message({
        message: '建议售价必须大于0',
        type: "error"
      });
      return;
    }
    if(val>this.result_spec[index].original_price){
      this.$message({
        message: '建议零售价必须小于等于原价',
        type: "error"
      });
      return;
    }
  }
  // 验证库存是否大于0
  getStock(val, index) {
    if (Number(val) <= 0) {
      this.result_spec[index].stock = null;
      this.$message({
        message: '库存必须大于0',
        type: "error"
      });
      return;
    }
  }
  // 添加规格项
  add() {
    this.specItems.push({
      standardValue: '',
      specNames: [],
      specName: '',
    });
  }
  // 删除规格值
  closeTag(i, index) {
    this.specItems[i].specNames.splice(index, 1);
    this.form.spec_item[i].children.splice(index, 1);
    // this.addSpec[i].children.splice(index, 1);
    // 规格值数组为空，则删除当前规格
    if (!this.specItems[i].specNames.length) {
      this.delliEle(i);
    }else{
      this.creatTable()
    }
  }
  // 删除规格项
  delliEle(index) {
    this.specItems.splice(index, 1);
    this.addSpec.splice(index, 1);
    if(this.form.spec_item.length>this.specItems.length){
      this.form.spec_item.splice(index, 1);
    }
    if (this.specItems.length === 0) {
      this.show = false;
    }
    this.arr.splice(index, 1);
    this.creatTable();
  }
  changeVal(index) {
    this.arr[index] = this.specItems[index].standardValue;
  }
  setParentInput(val, index) {
      this.arr[index] = val;
      let  newSpecItem = {};
      for (let item in this.specItems) {
          newSpecItem[this.specItems[item].standardValue] = this.specItems[item].specNames;
      }
      if (newSpecItem) {
          this.form.spec_item = newSpecItem;
      }
  }
  addSpecVal(index) {
    let that = this;
    let goods_id = this.form.id;

    for (let i = 0; i < this.specItems.length - 1; i++) {
      // if (this.specItems[index].standardValue === this.specItems[i].standardValue) {
      //   console.log(this.specItems[index])
      //   console.log(this.specItems[i])
      //   this.specItems[index].standardValue = '';
      //   this.specItems[index].specName = '';
      //   return;
      // }
    }
    if (!this.specItems[index].specName || !this.specItems[index].standardValue) return;
    this.$set(this.specItems[index], 'isTrigger', true);
    // 判断重复添加
    for (let i = 0; i < this.specItems[index].specNames.length; i++) {
      if (this.specItems[index].specName === this.specItems[index].specNames[i]) {
        return;
      }
    }
    this.specItems[index].specNames.push(this.specItems[index].specName);
    this.show = true;
    this.disable = true;
    // 请求添加规格接口并组装规格参数
    this.searchItem.item=this.specItems[index].standardValue
    this.searchItem.parent_id='0'
    this.searchItem.goods_id = goods_id;
    let a={id:"",item:"",parent_id:"",children:[]}
    let arr:any=[]
    if(this.specItems.length>this.addSpec.length){
      goodsApi.saveItem(this.searchItem)
      .then((res: any) => {
            a.id=res.data.data.id
            a.item=res.data.data.item
            a.parent_id=res.data.data.parent_id
        this.addSpec.push(a)
        this.searchItem2.item=this.specItems[index].specName
        this.searchItem2.parent_id = a.id
        this.searchItem2.goods_id = that.form.id;
        this.specItems[index].specName = '';
        goodsApi.saveItem(this.searchItem2)
        .then((res: any) => {
          let b={id:"",item:"",parent_id:a.id,children:[]}
              b.id=res.data.data.id
              b.item=res.data.data.item
          this.addSpec[index].children.push(b) 
          this.addSpec.forEach(item=>{
            if(item.children.length>0){
              arr.push(item)
            }
          })
          this.form.spec_item=arr
          this.creatTable();
        });
      })
    }
    else{
      this.searchItem2.item=this.specItems[index].specName
      this.searchItem2.parent_id=this.addSpec[index].id
      this.searchItem2.goods_id = this.form.id;
      this.specItems[index].specName = '';
      goodsApi.saveItem(this.searchItem2)
      .then((res: any) => {
        let b={id:"",item:"",parent_id:this.addSpec[index].id,children:[]}
            b.id=res.data.data.id
            b.item=res.data.data.item
        this.addSpec[index].children.push(b) 
        let arr:any=[]
        this.addSpec.forEach(item=>{
          if(item.children.length>0){
            arr.push(item)
          }
        })
        this.form.spec_item=arr
        this.creatTable();
      });
    }
  }
  creatTable() {
    let arr1:any=[]
    if(this.addSpec.length>0){
      this.addSpec.forEach((items:any,idx:any)=>{
      let itemOne=items
      let arr2:any=[]
      items.children.forEach((item:any,i:any)=>{
        arr2.push({
          key:items.id+":"+item.id,
          key_name : items.item + ":" + item.item,
          td:item.item,
        })
      })
      arr1.push(arr2);
      })
      this.specList(arr1);
    }else{
      this.result_spec=[]
      this.form.spec_goods_price=this.result_spec
    }
    console.log('spec_goods_price',this.form.spec_goods_price,this.result_spec)
  }

  specList(arr){
    let result:any = []
    let arrs=arr.shift()
    this.result_spec = arrs
    arr.forEach(item =>{
        this.specItem(this.result_spec,item)
    })
    this.result_spec.forEach(item=>{
      item.td=item.td.split(',')
    })
    let _arr:any=[]
    this.result_spec.forEach((item:any,i:any)=>{
      this.allDatas.spec_item_price.forEach((item2:any)=>{
        if(item.key_name==item2.key_name){
          
          item=item2
        }
      })
      _arr.push(item)
    })
    this.result_spec=_arr
    this.form.spec_item_price=this.result_spec
  }
  // 组合规格
  specItem(arr1,arr2){
    let result:any = []
    arr1.forEach(element => {
      arr2.forEach(element2 => {
        let a=element.key_name + '_' + element2.key_name
        result.push({
            key:element.key + '_' + element2.key,
            key_name:element.key_name + '_' + element2.key_name,
            td:element.td+','+element2.td,
            bar_code:"",//	条形码
            sku:"",//sku
            status:1,//状态
            price:"",//	规格售价
            original_price:0,//	原价
            suggest_price:"",//	建议售价
            channel_settle_price:"",//	渠道商结算价
            sell_price:"",//商家结算价
            platform_price:"",//供应商结算价
            vendor_price:"",//供应价
            stock: 0,//	库存
            spec_img:"",
            sale_stock:"",
            channelPrice:"",//渠道结算价
            supplierPrice:"",//商家结算价
          })
      })
    });
   this.result_spec = result;
  }
  // 一级分类
  handleChange(value:any) {
    this.kindList.forEach((item:any)=>{
      if(item.id==value){
        this.form.sub_cate_id = '';
        this.form.third_sub_cate_id = '';
        this.kindListTwo=item.children
      }
    })
  }
  // 二级分类
  handleChangeTwo(value){
    this.kindListTwo.forEach((item:any)=>{
      if(item.id==value){
        this.form.third_sub_cate_id = '';
        this.kindListThree=item.children
      }
    })
  }
  //修改上传海报
  codeediting() {
    this.isPoster = false
    this.isImport = true
  }
    // 海报
  posterImg(imgPath: any){
    this.form.share.share_bg = imgPath;
    this.form.share.type = 1
    this.form.share.qr_y = 0
    this.form.share.qr_x = 0
    this.isPoster = false
    this.isImport = true
  }
  determine(value) {
    console.log(value)
    this.form.share = value
    this.isPoster = false;
    this.isImport=false
  }
  //删除海报
  closeDialog() {
    this.isPoster = false;
    this.isImport=false
    this.form.share = {
      type:'',
      share_bg:'',
      qr_y:'',
      qr_x:''
    }
  }
  // 关闭弹窗
  closeDialog1() {
    console.log(this.form.share)
    this.isPoster = false;
    this.isImport=false
  }
  // 上传图片子组件传递过来的图片路径
  propImg(imgPath: any){
    this.form.cover = imgPath;
  }
  // 上传多张图片子组件传递过来的图片路径
  propImgList(imgPath: any){
    this.form.images = imgPath;
  }
  // 富文本编辑
  editorChange(data:any) {
    this.form.describe = data.content;
  }
  // 取消
  cancel(){
    this.$router.push({
      path:'/goodsList'
    })
  }
  shippingChange(){
    if(this.form.client == 0){
        this.form.shipping_id = ''
    }else{
        this.form.shipping_price =''
    }
  }
  shippingChange1(i:any) {
    this.form.client = i
    if(i == 0){
      this.form.shipping_id = ''
    }else if(i==1){
      this.form.shipping_price =''
    }
  }

  // 提交
  submitFormAdd(formName: any) {
    (this.$refs[formName] as any).validate((valid: boolean) => {
      console.log(valid)
      if (valid) {
        if(this.form.share.type==='' && this.form.share.share_bg==='') {
          this.form.share = {
            type:'',
            share_bg:'',
            qr_y:'',
            qr_x:''
          }
        }
        if(this.dateTime==null){
          this.dateTime=["",""]
        }
        if(this.saleDateTime==null){
          this.saleDateTime=["",""]
        }
        this.form.verify_start_time=this.dateTime[0];
        this.form.verify_end_time=this.dateTime[1];
        this.form.sale_on_time=this.saleDateTime[0];
        this.form.sale_off_time=this.saleDateTime[1];
        if(this.guige==1){
          this.form.spec_item=[]
          this.form.spec_goods_price=[]
          this.form.spec_item_price=[];
          this.result_spec = [];
          this.addSpec = [];
          this.specItems = [];
        }else {
          this.form.vendor_settle_price='0.00'
          this.form.channel_settle_price='0.00'
          this.form.merchant_settle_price='0.00'
          this.form.original_price='0.00'
          this.form.suggest_price='0.00'
          this.form.weight='0.00'
        }
        if(this.check) {
          let _this = this
          _this.check = false
          goodsApi.editGoods(this.form)
          .then((res: any) => {
            if(res.data.status){
              _this.$message({
                message: '操作成功',
                type: "success"
              });
              _this.$router.push({
                path:'/goodsList'
              })
              _this.$emit("loadData")
              setTimeout(function(){
                _this.check = true
              },3000)
            }else{
              _this.$message({
                message: res.data.msg,
                type: "error"
              });
              _this.check = true
            }
          });
        }
        
      }
    });
  }
  handleAvatarSuccess(res:any, file:any) {
    this.form.imgPath = res.data.fileUrl;
  }
  editorChangeRemark(data:any) {
      this.form.remark = data.content;
    }
  async loadData(){
    // 标签
    goodsApi.labelList(1,9999999)
      .then((res: any) => {
        this.labelList = res.data.data.data;
    });
    // 商家
    businessApi.businessList(1,999999,this.searchMapB)
      .then((res: any) => {
        this.businessList = res.data.data.list;
    });
    // 供应商
     supplierApi.supplierList(1,999999,this.searchMapS)
      .then((res: any) => {
        this.supplierList = res.data.data.lists.data;
    });
    //运费模板
    goodsApi.shippingTemplate().then((res: any) => {
      this.shippingTemplateList = res.data.data
    });

    //留言模板
    goodsApi.messageTemplate().then((res:any) => {
      this.messageTemplateList = res.data.data
    })

    // 详情
   await goodsApi.goodsDetail(this.$route.query.id)
    .then((res: any) => {
      this.timer=new Date().getTime()
      
      this.form=res.data.data
      this.allDatas=res.data.data
      let a=this.form.tag_ids
      let tag_ids:any=[]
      if(a.length>0){
          a.forEach((item:any)=>{
          item=parseInt(item);
          tag_ids.push(item)
        })
      }
      this.form.tag_ids=tag_ids
      console.log()
    //票付通商品
    console.log(res.data.data.share)
    if(!res.data.data.share) {
      this.form.share = {
        type:'',
        share_bg:'',
        qr_y:'',
        qr_x:''
      }
      
      
      
      
    }
    
    if(res.data.data.vendor_id==5) {
      this.getgetPftTicketList(res.data.data.id)
    }
  
    //物流为0的问题
    if(res.data.data.shipping_id == 0){
      this.form.shipping_id = '';
    }
      //一级 二级分类默认值为题
      if(res.data.data.sub_cate_id == 0){
        this.form.sub_cate_id = '';
        this.form.third_sub_cate_id = '';
      }

      if(res.data.data.third_sub_cate_id == 0){
      
        this.form.third_sub_cate_id = '';
      }


      if(this.form.verify_start_time && this.form.verify_end_time){
        this.dateTime=[this.form.verify_start_time,this.form.verify_end_time]
      }
      if(this.form.sale_on_time && this.form.sale_off_time){
        this.saleDateTime=[this.form.sale_on_time,this.form.sale_off_time]
      }
      // 组装 sku的商家结算价和渠道结算价，通过核销码的个数 * 价格做展示使用
      if(res.data.data.spec_item.length > 0 && res.data.data.spec_item_price.length > 0){
        this.guige=2
        this.addSpec=res.data.data.spec_item
        this.result_spec=res.data.data.spec_item_price
        this.result_spec.forEach((item:any)=>{
          let a = item.td
          item.td = []
          a=item.key_name.split('_')
          a.forEach((item2:any)=>{
          var index=item2.lastIndexOf("\:");
          item2=item2.substring(index+1,item2.length);
          item.td.push(item2)
          })
        })
        this.addSpec.forEach((items:any)=>{
          let a:any={standardValue: '',specNames: [],specName: '',}
          a.standardValue=items.item
          items.children.forEach((item:any,i:any)=>{
            let b=item.item
            a.specNames.push(b)
          })
          this.specItems.push(a)
        })
      }
      // 分类
      goodsApi.goodsKind()
        .then((res: any) => {
          this.kindList = res.data.data;
          this.kindList.forEach((items:any,i1)=>{
            if(items.children!==undefined) {
              items.children.forEach((item2:any,i2:any)=>{
                if(item2.id!==undefined) {
                  if(item2.id==this.form.sub_cate_id){
                    this.kindListTwo=this.kindList[i1].children
                    if(item2.children!==undefined) {
                      item2.children.forEach((item3:any)=>{
                        if(item3.id!==undefined) {
                          if(item3.id==this.form.third_sub_cate_id){
                            this.kindListThree=item2.children
                          }
                        }
                      })
                    }
                    
                  }
                }
              })
            }
          })
      });
    })
  }
  created() {
    this.loadData()
  }
  beforeUpdate() {
    if(this.form.shipping_id!==''){
      this.form.client = 1
    }else {
      this.form.client =0
    }
    if(this.form.shipping_price=='0.00') {
      this.form.shipping_price = ''
    }
  }
  //票付通商品门票内容
  getgetPftTicketList(id:any) {
    goodsApi.getPftTicketList(id)
    .then(re=>{
      console.log(re.data.data)
      let list  = re.data.data
      list.map(val=>{
        val.user_price=''
      })
      this.verifyList = list

      if(this.form.pft_ticket) {
        let pft_ticket = this.form.pft_ticket
        let arr = []
        for(let i = 0 ;i<list.length;i++) {
          for(let j = 0 ;j<pft_ticket.length;j++) {
            if(list[i].uuid==pft_ticket[j].uuid) {
                list[i]=pft_ticket[j]
            }
          }
        }
        this.toggleSelection(pft_ticket)
      }
    })
  }
  handleSelectionChange(val) {
    this.form.pft_ticket = val
  }
  toggleSelection(rows) {
    this.$nextTick(() => {
      if (rows) {
        rows.forEach(row => {
          (this.$refs.multipleTable as any).toggleRowSelection(row,true);
        });
      } else {
          (this.$refs.multipleTable as any).clearSelection();
      }
    })
    
    // console.log(rows)
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer{
  padding-left: 50px
}
.spec-box{
  border: 1px solid #d8d8d8;
  min-height: 200px;
  max-height: 800px;
  overflow-y: scroll;
  padding: 10px;
  .el-input,
  .el-select {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}
.form-box {
  margin-bottom: 20px;
  .el-input,
  .el-select {
    width: 200px !important;
  }
  .title{
    line-height: 60px;
    font-weight: bold;
    font-size: 16px;
  }
  .price-title{
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 20px;
  }
  .price-txt{
    font-size: 14px;
    color: #333;
  }
  .price-tip{
    color: red;
    font-size: 12px;
    margin-left: 50px;
  }
  .specBox {
    width: 75%;
    min-height: 200px;
    max-height: 800px;
    overflow-y: scroll;
    padding: 10px;
    border: 1px solid #d8d8d8;
    .specTable {
      border: 1px solid #e3e3e3;
      thead {
        background: #f5f5f5;
      }
      th,td {
        width: 120px;
        padding: 3px 8px;
        text-align: center;
        border: 1px solid #e3e3e3;
        .el-input{
          width: 100px !important;
        }
      }
    }
  }
}
.share_bg {
  width: 148px !important;
  height: 148px !important;
}
</style>
